package com.hcinfos.gsoo.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.chatuidemo.Constant;
import com.easemob.chatuidemo.db.UserDao;
import com.easemob.util.EMLog;
import com.easemob.util.HanziToPinyin;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.IntentUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * tab
 * 
 * @author john
 * 
 */
public class LoginActivity extends Activity implements OnClickListener {

	private TextView register_tv;

	private final int LOGIN_FAIL = 0x1120;
	private final int LOGIN_SUCCESS = LOGIN_FAIL + 1;
	private Dialog dialog;
	private SharePreferenceUtil util;
	private Context context;
	private Animation shake;

	private EditText userName_et;
	private EditText userPass_et;
	private Button login_bt;
	private ImageView back_iv;

	private ObjectMapper objectMapper;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		objectMapper = new ObjectMapper();
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		setContentView(R.layout.activity_login);
		util = new SharePreferenceUtil(this, "setting");
		this.context = this;
		dialog = DialogUtil.createProgressDialog(this, "登陆提示", "正在登陆中...");
		shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		initRes();
	}

	private void initRes() {
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		register_tv = (TextView) findViewById(R.id.register_tv);
		register_tv.setOnClickListener(this);

		userName_et = (EditText) findViewById(R.id.userName_et);
		userPass_et = (EditText) findViewById(R.id.userPass_et);

		login_bt = (Button) findViewById(R.id.login_bt);
		login_bt.setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		type = getIntent().getIntExtra("type", -1);
		super.onResume();
	};

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		String emailStr = getIntent().getStringExtra("email");
		String passwordStr = getIntent().getStringExtra("password");
		if (emailStr != null) {
			userName_et.setText(emailStr);
			userPass_et.setText(passwordStr);
		} else if (GsooApplication.ggNumber != null) {
			userName_et.setText(GsooApplication.ggNumber);
			userPass_et.setText(GsooApplication.password);
		}
		type = getIntent().getIntExtra("type", -1);
	}

	private Intent intent;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.register_tv:
			intent = new Intent(this, RegActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);
			break;
		case R.id.login_bt:
			boolean flag = loginCheck();
			if (flag) {
				if (dialog != null)
					dialog.show();
				doLogin();
			}

			break;
		case R.id.back_iv:

			finish();
			break;
		}
	}

	private boolean loginCheck() {
		String name = userName_et.getText().toString();
		String password = userPass_et.getText().toString();
		if (name.length() == 0) {
			userName_et.setHint("帐号不能为空");
			userName_et.startAnimation(shake);
			return false;
		}
		if (password.length() < 6) {
			userPass_et.setHint("密码不能少于6位数");
			userPass_et.startAnimation(shake);
			return false;
		}
		return true;
	}

	private void doLogin() {

		final String name = userName_et.getText().toString();
		final String password = userPass_et.getText().toString();

		HttpUtils http = UtilHttp.getHttpUtils(context);
		RequestParams params = new RequestParams();
		params.addBodyParameter("user.email", name);
		params.addBodyParameter("user.password", password);
		http.send(HttpRequest.HttpMethod.POST, Urls.NEW_USER_LOGIN, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						handler.sendEmptyMessage(LOGIN_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						LogUtil.d("wxf", "result:" + result);
						if (result == null) {
							Message msg = handler.obtainMessage();
							msg.what = LOGIN_FAIL;
							handler.sendMessage(msg);
						} else {
							try {
								JSONObject obj = new JSONObject(result);
								String message = obj.getString("message");
								int state = obj.getInt("state");
								if (state == 200) {

									User user = objectMapper.readValue(
											obj.getString("data"),
											new TypeReference<User>() {
											});
									if (user != null) {

										user.setPassword(userPass_et.getText()
												.toString());
										util.saveObject(user, "user");
										util.saveSharedPreferences("userName",
												user.getUsername());
										LogUtil.d("wxf",
												"user:" + user.getUsername());
										loginIM(user);
									}
									util.saveSharedPreferences("email", name);
									util.saveSharedPreferences("password",
											password);
								} else {
									Message msg = handler.obtainMessage();
									msg.obj = message;
									msg.what = LOGIN_FAIL;
									handler.sendMessage(msg);
								}
							} catch (Exception e) {
								LogUtil.e("wxf", e.toString());
								Message msg = handler.obtainMessage();
								msg.what = LOGIN_FAIL;
								handler.sendMessage(msg);
							}
						}
					}

				});

	}

	/**
	 * IM 登陆服务
	 */
	private void loginIM(final User user) {

		// final String username = "john1990";
		// final String password = "123456";
		// 调用sdk登陆方法登陆聊天服务器
		EMChatManager.getInstance().login("X" + user.getGgnumber(),
				user.getPassword(), new EMCallBack() {

					@Override
					public void onSuccess() {
						// 登陆成功，保存用户名密码
						GsooApplication.getInstance().setUserName(
								user.getUsername());
						GsooApplication.getInstance().setPassword(
								user.getPassword());
						try {
							// demo中简单的处理成每次登陆都去获取好友username，开发者自己根据情况而定
							List<String> usernames = EMChatManager
									.getInstance().getContactUserNames();
							Map<String, com.easemob.chatuidemo.domain.User> userlist = new HashMap<String, com.easemob.chatuidemo.domain.User>();
							for (String username : usernames) {
								com.easemob.chatuidemo.domain.User user = new com.easemob.chatuidemo.domain.User();
								user.setUsername(username);
								setUserHearder(username, user);
								userlist.put(username, user);
							}
							// 添加user"申请与通知"
							com.easemob.chatuidemo.domain.User newFriends = new com.easemob.chatuidemo.domain.User();
							newFriends
									.setUsername(Constant.NEW_FRIENDS_USERNAME);
							newFriends.setNick("申请与通知");
							newFriends.setHeader("");
							userlist.put(Constant.NEW_FRIENDS_USERNAME,
									newFriends);
							// 添加"群聊"
							com.easemob.chatuidemo.domain.User groupUser = new com.easemob.chatuidemo.domain.User();
							groupUser.setUsername(Constant.GROUP_USERNAME);
							groupUser.setNick("群聊");
							groupUser.setHeader("");
							userlist.put(Constant.GROUP_USERNAME, groupUser);

							// 存入内存
							GsooApplication.getInstance().setContactList(
									userlist);
							// 存入db
							UserDao dao = new UserDao(LoginActivity.this);
							List<com.easemob.chatuidemo.domain.User> users = new ArrayList<com.easemob.chatuidemo.domain.User>(
									userlist.values());
							dao.saveContactList(users);

							// 获取群聊列表(群聊里只有groupid和groupname的简单信息),sdk会把群组存入到内存和db中
							EMGroupManager.getInstance().getGroupsFromServer();
							handler.sendEmptyMessage(LOGIN_SUCCESS);

						} catch (Exception e) {
							handler.sendEmptyMessage(LOGIN_FAIL);

							LogUtil.e("wxf", e.toString());
						}
						boolean updatenick = EMChatManager.getInstance()
								.updateCurrentUserNick(
										GsooApplication.currentUserNick);
						if (!updatenick) {
							EMLog.e("LoginActivity",
									"update current user nick fail");
						}

					}

					@Override
					public void onError(int arg0, String arg1) {
						handler.sendEmptyMessage(LOGIN_SUCCESS);
						LogUtil.e("wxf", "IM 登陆错误=" + arg1);
					}

					@Override
					public void onProgress(int arg0, String arg1) {

					}
				});
	}

	private int type = -1;
	Handler handler = new Handler() {

		public void handleMessage(Message msg) {

			if (dialog != null)
				dialog.dismiss();
			switch (msg.what) {
			case LOGIN_FAIL:
				if (msg.obj != null) {
					String msgStr = (String) msg.obj;
					Toast.makeText(context, msgStr, 500).show();
				}
				break;
			case LOGIN_SUCCESS:
				Toast.makeText(LoginActivity.this, "登陆成功", 500).show();
				if (type != -1) {
					setResult(RESULT_OK);
					finish();
				} else {
					IntentUtil.start_activity(LoginActivity.this,
							MainTabActivity.class);
					sendBroadcast(new Intent("com.login.update.action"));
					finish();
				}
				break;
			}
		};
	};

	/**
	 * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
	 * 
	 * @param username
	 * @param user
	 */
	protected void setUserHearder(String username,
			com.easemob.chatuidemo.domain.User user) {
		String headerName = null;
		if (!TextUtils.isEmpty(user.getNick())) {
			headerName = user.getNick();
		} else {
			headerName = user.getUsername();
		}
		if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
			user.setHeader("");
		} else if (Character.isDigit(headerName.charAt(0))) {
			user.setHeader("#");
		} else {
			user.setHeader(HanziToPinyin.getInstance()
					.get(headerName.substring(0, 1)).get(0).target.substring(0,
					1).toUpperCase());
			char header = user.getHeader().toLowerCase().charAt(0);
			if (header < 'a' || header > 'z') {
				user.setHeader("#");
			}
		}
	}

	public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	};
}
